package acc_service

import (
	"chat-room/providers"
	"chat-room/websocket/acc_dao"
	"encoding/json"
	"errors"
	"time"
)

type LogService struct {
}

/**
 * @Author: yang
 * @Description： 推送信息模板
 * @Date: 2021/11/2 19:56
 */
type SendMsg struct {
	Type     int    `json:"type"`
	UserName string `json:"user_name"`
	Content  string `json:"content"`
	CreateAt string `json:"create_at"`
}

/**
 * @Author: yang
 * @Description：聊天记录保存
 * @Date: 2021/11/2 16:57
 */
func (ls *LogService) SaveLog(msg string, token string, t int) error {
	tx := providers.Mysql

	userDao := acc_dao.User{}
	user, err := userDao.Find(tx, &acc_dao.User{
		Token:    token,
		IsDelete: 0,
	})
	if err != nil {
		return errors.New("用户不存在")
	}

	logDao := &acc_dao.Log{
		UserId:  user.Id,
		RoomId:  user.RoomId,
		Type:    t,
		Content: msg,
	}
	err = logDao.Save(tx)
	if err != nil {
		return errors.New("添加记录失败")
	}

	return nil
}

/**
 * @Author: yang
 * @Description： 生成推送消息模板--json格式化
 * @Date: 2021/11/2 20:05
 */
func (ls *LogService) ProductLog(msg string, token string, t int) (m string) {

	tx := providers.Mysql
	userDao := acc_dao.User{}
	user, err := userDao.Find(tx, &acc_dao.User{
		Token:    token,
		IsDelete: 0,
	})
	if err != nil {
		return
	}

	sendMsg := SendMsg{
		UserName: user.Name,
		Content:  msg,
		Type:     t,
		CreateAt: time.Unix(time.Now().Unix(), 0).Format("2006-01-02 15:04:05"),
	}

	jsonBytes, err := json.Marshal(sendMsg)
	if err != nil {
		return
	}

	m = string(jsonBytes)
	return
}
